package com.dk.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dk.pojo.TPerson;
import com.dk.service.MenuService;
import com.dk.service.TpersonService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

//Realm :专门用来书写登录授权逻辑

public class LoginController extends AuthorizingRealm {
    @Reference
    private TpersonService tpersonService;
    @Reference
    private MenuService menuService;
   //授权用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        TPerson prems = (TPerson) SecurityUtils.getSubject().getPrincipal();
        List<String> list = menuService.selectByPid(prems.getPid());
        sai.addStringPermissions(list);
        return sai;
    }
//登录用
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String pname = token.getUsername();
        TPerson person = tpersonService.selectInfo(pname);
        if (person == null){
            return null;
        }
        System.out.println(token.getPassword());
        return new SimpleAuthenticationInfo(person,person.getPwd(), ByteSource.Util.bytes(person.getSalt()),person.getPname());
    }
}
